<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Http\Requests\V1\TransformerRequest;
use App\Models\V1\BasicCollectors;
use App\Models\V1\BasicCustomers;
use App\Models\V1\BasicTransformers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use League\Flysystem\Exception;
use Log;
use DB;

class TransformersController extends Controller
{
    /**
     * 显示变压器数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('v1.transformers');
    }

    /**
     * 获取变压器数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的变压器数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');

        // 获取符合查询条件的变压器数据
        $data = $this->getTransformersList($currentPage, $rows, $keywords);

        if (!$data->isEmpty()) {

            $formatList = array();

            $count = $data->total() > 0 ? $data->total() : 0;

            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $customerObj = $item->customer;
                    $collector = $this->getCollectorByCode($item['code']);
                    $formatItem['code'] = $item['code'];
                    $formatItem['model_code'] = $item['model_code'];
                    $formatItem['customer_transformer_code'] = $item['customer_transformer_code'];
                    $formatItem['customer_code'] = $customerObj['name'];
                    $formatItem['collector_code'] = $collector['code'];
                    $formatItem['collector_mac_code'] = $collector['mac_code'];
                    $formatItem['model'] = $item['model'];
                    $formatItem['capacity'] = $item['capacity'];
                    $formatItem['address'] = $item['address'];
                    $formatItem['remark'] = $item['remark'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }

                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }

        return $response;
    }

    /**
     * 进入单条变压器数据显示界面 (适用于新增addData、查看viewData、编辑editData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        switch ($request->input('view')){
            case 'addData':
                $data['randomCode'] = 'TSR' . uniqid();
                $data['customers'] = $this->getCustomersList();
                return view('v1.form.transformer_item', $data);
                break;
            case 'editData':
                $collector = $this->getCollectorByCode($request->input('code'));
                $data['code'] = $request->input('code');
                $transformers = $this->getTransformerByCode($data['code']);
                $data['customers'] = $this->getCustomersList();
                $data['collector_code'] = empty($collector) ? NULL : $collector['code'];
                $data['collector_mac_code'] = empty($collector) ? NULL : $collector['mac_code'];
                $data['itemData'] = $transformers;
                return view('v1.form.transformer_item', $data);
                break;
            case 'viewData':
                $collector = $this->getCollectorByCode($request->input('code'));
                $data['code'] = $request->input('code');
                $transformers = $this->getTransformerByCode($data['code']);
                $data['collector_code'] = $collector['code'];
                $data['itemData'] = $transformers;
                return view('v1.form.transformer_item', $data);
                break;

        }
    }

//    /**
//     * 显示变压器数据导入页面
//     *
//     * @param Request $request
//     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
//     */
//    public function importView(Request $request)
//    {
//        // 获取登录用户
//        $loginUser = Auth::user();
//
//        $data['view'] = $request->input('view');
//        $data['code'] = $loginUser->getAttribute('code');
//
//        return view('v1.form.upload_excel', $data);
//    }

    /**
     * 更新变压器基本信息(单元格)
     *
     * @param TransformerRequest $request
     * @return array
     */
    public function updateCellData(TransformerRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '变压器代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateTransformer($request);

            // 更新变压器信息
            $successFlag = $this->handleUpdate($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '变压器代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 更新变压器基本信息
     *
     * @param TransformerRequest $request
     * @return array
     */
    public function updateData(TransformerRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '变压器代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateTransformer($request);

            // 更新变压器信息
            $successFlag = $this->handleUpdate($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '变压器代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 新增基本信息
     *
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '变压器[' . $request->input('code') . '],新增失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $rules['code'] = 'bail|required';
            $rules['model_code'] = 'bail|required';
            $rules['customer_code'] = 'bail|required|exists:basic_customers,code,deleted_at,NULL';
//            $rules['captcha'] = 'bail|required|captcha';
            $messages['code.required'] = '变压器代码不能为空';
            $messages['model_code.required'] = '变压器编码不能为空';
            $messages['customer_code.required'] = '客户代码不能为空';
            $messages['customer_code.exists'] = '客户代码不存在';
//            $messages['captcha.required'] = '验证码不能为空';
//            $messages['captcha.captcha'] = '验证码错误';

            $this->validate($request, $rules, $messages);

            // 新增信息
            $successFlag = $this->handleAdd($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '变压器[' . $request->input('code') . '],新增成功！';
            }
        }

        return $response;
    }

    /**
     * 删除变压器基本信息
     *
     * @param TransformerRequest $request
     * @return array
     */
    public function deleteData(TransformerRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '变压器代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateTransformer($request);

            // 删除变压器信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '变压器代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除变压器基本信息
     *
     * @param TransformerRequest $request
     * @return array
     */
    public function deleteBatchData(TransformerRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '变压器批量删除失败！',
        ];

        if ($request->method() === 'POST') {

            // 删除变压器信息
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '变压器批量删除成功！';
            }
        }

        return $response;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的变压器列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getTransformersList($page = 1, $rows, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = BasicTransformers::orderBy('created_at', 'asc')->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = BasicTransformers::where('name', 'like', '%' . $keywords . '%')->orderBy('created_at', 'asc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }

    /**
     * 根据变压器代码获取对应变电站信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getTransformerByCode($code)
    {
        $transformer = BasicTransformers::where('code', $code)->first();
//        $customer = $transformer->customer;
//        $customer['customer_code'] = $customer['name'];
        return $transformer;
    }

    /**
     * 根据变压器代码获取对应的采集器信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getCollectorByCode($code)
    {
        $collector = BasicCollectors::where('transformer_code', $code)->first();
        return $collector;
    }

    /**
     * 获取所有的客户列表信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getCustomersList()
    {
        $data = BasicCustomers::get(['code', 'name']);
        return $data;
    }


    ///////////////////////////////////////////////////////////////////
    /// 验证表单请求功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新变压器信息验证请求
     *
     * @param Request $request
     */
    private function validateTransformer(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新变压器信息
     *
     * @param Request $request
     * @param bool $bCell 是否为单元格修改数据
     * @return bool
     */
    private function handleUpdate(Request $request, $bCell)
    {
        $where = $request->input('code');

        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            // 拼装更新数据数组
            $updateData = array();
            $counter = 0;
            foreach ($attrs as $attr) {
                $updateData[$attr] = $values[$counter];
                $counter++;
            }

            // 更新变压器信息
            $rspObj = BasicTransformers::where('code', $where)
                ->update($updateData);
            return $rspObj;

        } else { // 表单修改
            // 拼装更新数据数组
            $updateData = [
                'model_code' => $request->input('model_code'),
                'customer_code' => $request->input('customer_code'),
            ];
             if ($request->input('customer_transformer_code') !== "") {
                 $updateData['customer_transformer_code'] = $request->input('customer_transformer_code');
             }
            if ($request->input('address') !== "") {
                $updateData['address'] = $request->input('address');
            }
            if ($request->input('model') !== "") {
                $updateData['model'] = $request->input('model');
            }
            if ($request->input('capacity') !== "") {
                $updateData['capacity'] = $request->input('capacity');
            }
            if ($request->input('remark') !== "") {
                $updateData['remark'] = $request->input('remark');
            }
        }

        DB::beginTransaction(); // 开启事务
        $successFlag = false;
        try{
            // 更新变压器信息
            $rspObj = BasicTransformers::where('code', $where)
                ->update($updateData);
            // 判断是否绑定了采集器
            if ($rspObj){
                // 之前绑定了采集器
                if (isset($request['collector_code']) && !empty($request['collector_code'])) {
                    $collector_code = $request->input('collector_code');
                    $updateCollectorData = [
                        'code' => $request->input('collector_code'),
                        'transformer_code' => $request->input('code'),
                    ];
                    if ($request->input('collector_mac_code') !== "") {
                        $updateCollectorData['mac_code'] = $request->input('collector_mac_code');
                    }
                    if ($request->input('model') !== "") {
                        $updateData['model'] = $request->input('model');
                    }
                    $rspTag = BasicCollectors::where('code',$collector_code)
                        ->update($updateCollectorData);
                    $successFlag = $rspTag;
                }else{ // 之前未绑定采集器，新增绑定
                    // 绑定采集器信息
                    $insertCollectorData = [
                        'code' => 'CTR' . uniqid(),
                        'mac_code' => isset($request['collector_mac_code']) ? $request->input('collector_mac_code') : NULL,
                        'transformer_code' => $request->input('code'),
                        'model' => isset($request['model']) ? $request->input('model') : NULL,
                    ];
                    $insertTag = BasicCollectors::create($insertCollectorData);
                    if ($insertTag){
                        $successFlag = true;
                    }
                }
            }else{
                $successFlag = $rspObj;
            }

            if (!$successFlag){
                DB::rollBack();
            }else{
                DB::commit();
            }
            return $successFlag;
        }catch (Exception $exception){
            DB::rollback();
            return $successFlag;
        }
        return $successFlag;
    }

    /**
     * 处理更新变压器信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        // 开启事务
        DB::beginTransaction();
        $where = $request->input('code');
        // 全部删除的标志,0:默认值，1：删除失败， 2全部删除成功
        $allDeleteTag = '0';

        if ($bBatch) { // 批量删除
            $codeList = $request->input('code');
            foreach ($codeList as $code) {
                $deleteTag = $this->deleteTransformer($code);
                if (!$deleteTag){
                    $allDeleteTag = '1';
                    break;
                }else{
                    $allDeleteTag = '2';
                }
            }

            //全部成功删除时，事务commit
            if ($allDeleteTag === '2'){
                DB::commit();
                return true;
            }else{
                DB::rollBack();
                return false;
            }
        } else { // 单条删除
            $deleteTag = $this->deleteTransformer($where);
            if (!$deleteTag){
                DB::rollBack();
                return false;
            }else{
                DB::commit();
                return true;
            }
        }
    }

    /**
     * 处理新增信息
     *
     * @param Request $request
     * @return bool
     */
    private function handleAdd(Request $request)
    {
        DB::beginTransaction(); // 开启事务
        $successFlag = false;
        try{
            // 拼装新增数据数组
            $insertData = [
                'code' => $request->input('code'),
                'model_code' => $request->input('model_code'),
                'customer_transformer_code' => isset($request['customer_transformer_code']) ? $request->input('customer_transformer_code') : NULL,
                'customer_code' => $request->input('customer_code'),
                'model' => isset($request['model']) ? $request->input('model') : NULL,
                'capacity' => isset($request['capacity']) ? $request->input('capacity') : NULL,
                'address' => isset($request['capacity']) ? $request->input('capacity') : NULL,
                'remark' => isset($request['remark']) ? $request->input('remark') : NULL,
            ];
            $rspObj = BasicTransformers::create($insertData);
            if ($rspObj && isset($request['collector_mac_code']) &&!empty($request['collector_mac_code']) ){
                // 绑定采集器信息
                $insertCollectorData = [
                    'code' => 'CTR' . uniqid(),
                    'mac_code' => $request->input('collector_mac_code'),
                    'transformer_code' => $request->input('code'),
                    'model' => isset($request['model']) ? $request->input('model') : NULL,
                ];
               $rspTag =  BasicCollectors::create($insertCollectorData);
               if ($rspTag){
                   $successFlag = true;
               }
            }else{
                if ($rspObj){
                    $successFlag = true;
                }
            }
            if (!$successFlag){
                DB::rollBack();
            }else{
                DB::commit();
            }
            return $successFlag;
        }catch (Exception $exception){
            DB::rollback();
            return $successFlag;
        }
    }

    /**
     *  处理变压器的删除，删除关联表的相关数据
     * @param Request $request
     * @return bool
     */
    private function deleteTransformer($code)
    {
        $allDeleteTag = '1';
        $transformerObj = BasicTransformers::where('code',$code)->first();
        if (!empty($transformerObj)) {
            // 查询是否有采集器关联了此变压器
            $collectorObj = BasicCollectors::where('transformer_code',$code)->first();
            if ($collectorObj) {
                // 删除采集器
                $collectorDeleteTag = $collectorObj->delete();
                if (!$collectorDeleteTag){
                    return false;
                }else{
                    $allDeleteTag = '2';
                }
            }else{
                $allDeleteTag = '2';
            }
        }else{
            $allDeleteTag = '2';
        }

        // 删除变压器
        if ($allDeleteTag === '1'){
            return false;
        }else{
            $transformerTag = $transformerObj->delete();
            if (!$transformerTag){
                return false;
            }else{
                return true;
            }
        }
    }
}
